package main

import (
	myApp "guns-excel/internal/app"
	"guns-excel/internal/app/controller"
	"guns-excel/internal/pkg/app"
	"guns-excel/internal/pkg/config"
	"guns-excel/internal/pkg/cron"
	"guns-excel/internal/pkg/database"
	"guns-excel/internal/pkg/log"
	"guns-excel/internal/pkg/transports/http"
	"guns-excel/internal/pkg/util"
)

// 初始化资源
func CreateApp(path string) (*app.Application, error) {
	// 实例化viper
	viper, err := config.NewViper(path)
	if err != nil {
		return nil, err
	}
	// 实例化日志
	logOptions, err := log.NewOptions(viper)
	if err != nil {
		return nil, err
	}
	if err = log.New(logOptions); err != nil {
		return nil, err
	}
	// 实例化mysql
	mysqlOptions, err := database.NewOptions(viper)
	if err != nil {
		return nil, err
	}
	if err = database.NewMysql(mysqlOptions); err != nil {
		return nil, err
	}
	fn := controller.CreateInitControllersFn()
	router := http.NewRouter(fn)
	// 实例化http程序
	fiberOptions, err := http.NewOptions(viper)
	if err != nil {
		return nil, err
	}
	httpServer, err := http.New(fiberOptions, router)
	if err != nil {
		return nil, err
	}
	// app应用
	myAppOptions, err := myApp.NewOptions(viper)
	if err != nil {
		return nil, err
	}
	// 初始化雪花算法
	util.NewSnowflake("2020-01-01", 1)
	// 初始化cron
	cron.NewCron()
	app, err := myApp.NewApp(myAppOptions, httpServer)
	if err != nil {
		return nil, err
	}
	return app, nil
}
